﻿using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Input;
using Azukit.WPF.Command;
using Azukit.WPF.ViewModel;
using Hibiku.Services;
using Hibiku.Twitter;
using Hibiku.Views;

namespace Hibiku.ViewModels
{
    public class AuthorizationViewModel : ViewAwareViewModelBase
    {
        public ICommand AuthorizeCommand
        {
            get;
            private set;
        }

        private readonly ITwitterApi m_api;
        private readonly IApplicationConfigurationService m_configurationService;

        public AuthorizationViewModel(ITwitterApi api, IApplicationConfigurationService configurationService)
        {
            m_api = api;
            m_configurationService = configurationService;

            AuthorizeCommand = new DelegatingCommand(x => DoAuthorize());
        }

        public void DoAuthorize()
        {
            var authorizationRequest = m_api.GetAuthorizationRequest();

            Process.Start(authorizationRequest.Url);

            var dialog = new InputPinView();
            if (dialog.ShowDialog() == true)
            {
                var pin = dialog.Pin;

                try
                {
                    m_api.Authorize(pin, authorizationRequest.RequestTokenPair);

                    CloseView();
                }
                catch (Exception)
                {
                    if (MessageBox.Show("Authorization failed. Authorize again?", "Authorization failed", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                    {
                        DoAuthorize();
                    }
                    else
                    {
                        Environment.Exit(1);
                    }
                }
            }
            else
            {
                if (MessageBox.Show("No PIN entered. Authorize again?", "Authorization failed", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                {
                    DoAuthorize();
                }
                else
                {
                    Environment.Exit(1);
                }
            }
        }
    }
}
